package com.xinchengxd.order.service.impl;

import com.xinchengxd.commons.ResponseResult;
import com.xinchengxd.commons.entity.dto.GoodsNums;
import com.xinchengxd.commons.entity.dto.MailDTO;
import com.xinchengxd.commons.entity.dto.OrderDTO;
import com.xinchengxd.commons.entity.goods.Goods;
import com.xinchengxd.commons.entity.order.Order;
import com.xinchengxd.commons.entity.order.OrderItem;
import com.xinchengxd.commons.entity.user.User;
import com.xinchengxd.order.mapper.OrderMapper;
import com.xinchengxd.order.service.GoodsService;
import com.xinchengxd.order.service.OrderService;
import com.xinchengxd.order.service.UserService;
import com.xinchengxd.order.utils.OrderNoUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: 姚新成
 * @Date: 2021/11/9:22:34
 * @Description:
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    OrderMapper orderMapper;
    @Resource
    UserService userService;
    @Resource
    GoodsService goodsService;
    @Autowired
    AmqpTemplate amqpTemplate;


    @Override
    public Boolean isPay(String orderNo) {
        String status = orderMapper.isPay(orderNo);
        System.out.println("status是："+ status);
        if(status==null){
            return false;
        }
        /*Y表示已完成支付*/
        return status.equals("Y");
    }

    @Override
    @Transactional
    @GlobalTransactional
    public Order place(OrderDTO orderDTO) {

        /*初始数据准备*/
        BigDecimal money = new BigDecimal(0);
        List<OrderItem> items = new ArrayList<>();
        Order order = new Order();

        order.setUser(new User(orderDTO.getUserId()));
        order.setAccept(orderDTO.getAccept());
        order.setTelephone(orderDTO.getTelephone());
        order.setAddress(orderDTO.getAddress());

        /*订单号生成*/
        OrderNoUtil uuidNo = new OrderNoUtil("A","028");
        String orderNo = uuidNo.getOrderNo();

        order.setOrderNo(orderNo);
        order.setPayType("2");
        order.setOrderTime(new Date());
        order.setPayTime(new Date());
        order.setIsDel("N");
        order.setStatus("N");

        System.out.println("接受的的DTO：" + orderDTO);

        /*取出商品列表，向Goods查各个商品的价格和库存*/
        List<GoodsNums> item = orderDTO.getItem();
        ResponseResult<List<Goods>> res = goodsService.getPrice(item);
        System.out.println("res:" + res);

        /*计算金额并设置money*/
        List<Goods> list = res.getData();

        /*计算金额并设置money*/
        for (int i = 0; i < item.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (item.get(i).getGoodsId() == list.get(j).getId()) {
                    GoodsNums tempgn = item.get(i);
                    Goods tempg = list.get(j);
                    /*计算总金额*/
                    BigDecimal temp = new BigDecimal(tempgn.getNums());
                    temp = temp.multiply(tempg.getPrice());
                    money = money.add(temp);
                    System.out.println("进入金额计算：" + temp);

                    /*设置orderItem*/
                    items.add(new OrderItem(
                            new Goods(tempgn.getGoodsId()), tempgn.getNums(), tempg.getPrice())
                    );
                    break;
                }
            }
        }
        System.out.println("总金额：" + money);
        order.setMoney(money);

        /*保存订单*/
        int total = orderMapper.saveOrder(order);
        /*取出订单id 保存订单详细*/
        if (total == 1) {
            int id = order.getId();
            for (int i = 0; i < items.size(); i++) {
                items.get(i).setOrder(new Order(id));
            }
        }
        int total2 = orderMapper.saveItem(items);

        /*调用库存修改接口 （可在对端增加批量修改）*/
        for (GoodsNums g : item
        ) {
            Integer id = g.getGoodsId();
            Integer num = -g.getNums();
            ResponseResult<String> stockRes = goodsService.updateStock(id, num);

            //如果修改失败 抛出异常进行事务回滚
            if (stockRes.getCode() == 601) {
                throw new RuntimeException("库存不足");
            }
            System.out.println("库存:" + id + "修改：" + stockRes);
        }

        /*调用用户积分修改接口*/

        Integer id = orderDTO.getUserId();
        Integer change = order.getMoney().intValue();
        ResponseResult<String> pointRes = userService.updatePoint(id, change);
        System.out.println("修改积分：" + pointRes);


        /*用户信息 userName,email*/
        ResponseResult<User> userInfo = userService.lookbyid(orderDTO.getUserId());
        User user = userInfo.getData();

        /*收货信息*/
        String accept = orderDTO.getAccept();
        String telephone = orderDTO.getTelephone();
        String address = orderDTO.getAddress();
        String orderNo1 = order.getOrderNo();

        /*发送mailDTO到队列*/
        MailDTO mail = new MailDTO(user.getEmail(), user.getNickname(), orderNo1, accept, telephone, address, items);
        /*发送到订单队列*/
        amqpTemplate.convertAndSend("yxc_mail_exchange", "order_mail", mail);
        /*发送到支付队列*/
        amqpTemplate.convertAndSend("yxc_mail_exchange", "order_pay", mail);

        return order;
    }


}
